/* eslint-disable no-shadow */
/**
 * BOSS直聘
 */
import React from 'react';
import { Form, Input, Select, Row, Col, Button, message, Card, Icon, Alert, Spin } from 'antd';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import DropDownCascader from '../../Setting/containers/DropDownCascader';
import { getCategoryTree, getPositionKeywords } from '../../Setting/service';
import { arrJobType } from './bossStaticDict';
import useChannelDict from './useChannelDict';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';

const { Option } = Select;
const channelCode = 'bosszp';
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
    }
};
const renderOptionsMoney = () => {
    const arr = [];
    for (let i = 1; i <= 250; i += 1) {
        arr.push({
            value: i,
            title: `${i}k`
        });
    }

    return arr.map(item => (
        <Option value={item.value} key={item.value}>
            {item.title}
        </Option>
    ));
};

const renderMonthForm = () => {
    const arr = [];
    for (let i = 12; i <= 24; i += 1) {
        arr.push(i);
    }
    return arr.map(item => (
        <Option value={String(item)} key={String(item)}>
            {item}
        </Option>
    ));
};
const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));
const flat = tree =>
    tree.reduce((pre, curr) => {
        const { children, label, value } = curr;
        let next = [{ label, value }];
        if (children && children.length) {
            next = [...next, ...flat(children)];
        }
        return [...pre, ...next];
    }, []);
function BossForm({ form, outwardId, onSuccess, onError }) {
    const { getFieldDecorator, getFieldsValue, getFieldValue, validateFields } = form;
    const { workExperience, educationDegree, loading: dictLoading } = useChannelDict(channelCode, [
        'workExperience',
        'educationDegree'
    ]);
    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);
    const [data, loading] = useRecruitOutwardsChannelDetail(outwardId, channelCode);
    // 职位类别树
    const { data: categoryTree, loading: categoryLoading } = useRequest(() => getCategoryTree(channelCode), {
        refreshDeps: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return null;
        }
    });
    // 关键词列表
    const { data: keywords, loading: keywordLoading, run: fetchKeywords, mutate: resetKeywords } = useRequest(
        getPositionKeywords,
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );

    // DropDownCascader存在问题： onChange事件只要值变化就会触发（不是手动选择后触发），因而添加了这个状态去控制职位关键词是否清空
    const firstChangeRef = React.useRef(false);
    const handlePositionChange = keys => {
        if (keys && keys.length > 0) {
            fetchKeywords({
                channelCode,
                positionCategoryCodeList: keys
            });
        } else {
            resetKeywords([]);
        }
        if (firstChangeRef.current) {
            firstChangeRef.current = !firstChangeRef.current;
        } else {
            form.setFieldsValue({
                skillList: undefined
            });
        }
    };
    React.useEffect(() => {
        const channelRecruitInfo = JSON.parse(data?.channelRecruitInfo || null);
        if (!channelRecruitInfo) {
            return;
        }
        console.log(channelRecruitInfo);
        firstChangeRef.current = true;
        const { position } = channelRecruitInfo;
        const extend = {
            position: position ? [position] : []
        };
        const values = { ...channelRecruitInfo, ...extend };
        const formValues = getFieldsValue();
        const exists = key => Object.keys(formValues).indexOf(key) !== -1;
        form.setFieldsValue(
            Object.keys(values).reduce((pre, curr) => {
                if (exists(curr)) {
                    return { ...pre, [curr]: values[curr] };
                }
                return { ...pre };
            }, {})
        );
    }, [data]);
    const handleSubmit = e => {
        e.preventDefault();

        form.validateFieldsAndScroll(async (err, values) => {
            if (err) {
                return;
            }
            const flatArr = flat(categoryTree);
            const { position } = values;
            // const locationItem = arrBossWorkPlace.find(item => item.Geocoder === Geocoder) || {};
            const extend = {
                position: position.join(','),
                positionCategory: position
                    .map(id => flatArr.find(item => item.value === id)?.label)
                    .filter(_ => _)
                    .join(',')
                // ...locationItem
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...values, ...extend }));
        });
    };

    const renderJobTypeOptions = () =>
        arrJobType.map(item => (
            <Option value={item.Id} key={item.Id} disabled={item.Id !== '0'}>
                {item.Name}
            </Option>
        ));
    // const renderWorkPlaceOptions = () =>
    //     arrBossWorkPlace.map(item => (
    //         <Option value={item.Geocoder} key={item.Geocoder}>
    //             {item.work_place}
    //         </Option>
    //     ));
    // 标准的
    const renderOptions = dict => {
        if (!dict || !dict.length) {
            return null;
        }
        return dict.map(item => (
            <Option value={item.selectValue} key={item.selectValue}>
                {item.selectName}
            </Option>
        ));
    };
    const checkPrice = (rule, value, callback) => {
        const from = getFieldValue('lowSalary');
        const to = getFieldValue('highSalary');
        if (!from || !to) {
            return callback('请输入职位参考月薪');
        }
        if (from - to > 0) {
            return callback('薪资最小值不能大于最大值');
        }
        return callback();
    };
    const handleForceValidate = keys => {
        validateFields(keys, { force: true });
    };
    React.useEffect(() => {
        handleForceValidate(['temp']);
    }, [getFieldValue('lowSalary'), getFieldValue('highSalary')]);
    const renderSalaryForm = () =>
        getFieldDecorator('temp', {
            initialValue: 1,
            rules: [{ required: true, message: '\r' }, { validator: checkPrice }]
        })(
            <div style={{ display: 'flex' }}>
                <Form.Item label="" colon={false} style={{ width: '33%', marginBottom: 0 }}>
                    {getFieldDecorator('lowSalary')(<Select placeholder="最低薪资">{renderOptionsMoney()}</Select>)}
                </Form.Item>
                <span style={{ margin: '0 8px' }}>-</span>
                <Form.Item label="" colon={false} style={{ width: '33%', marginBottom: 0 }}>
                    {getFieldDecorator('highSalary')(<Select placeholder="最高薪资">{renderOptionsMoney()}</Select>)}
                </Form.Item>
                <span style={{ margin: '0 8px' }}>X</span>
                <Form.Item label="" colon={false} style={{ width: '30%', marginBottom: 0 }}>
                    {getFieldDecorator('salaryMonth')(<Select placeholder="月份">{renderMonthForm()}</Select>)}
                </Form.Item>
                <Form.Item label="" colon={false} style={{ marginLeft: 10 }}>
                    {/* {data?.companyCurrencyCode || '薪'} */}薪
                </Form.Item>
            </div>
        );

    const renderSKillForm = () => (
        <Form.Item label="职位关键词">
            <Spin spinning={keywordLoading}>
                {getFieldDecorator('skillList', {
                    initialValue: undefined,
                    rules: [
                        {
                            required: true,
                            message: '请选择或输入职位关键词'
                        },
                        {
                            validator(rule, value, callback) {
                                if (value?.length > 8) {
                                    callback('职位关键词不能超过8个');
                                    return;
                                }
                                callback();
                            }
                        }
                    ]
                })(
                    <Select
                        showArrow
                        mode="tags"
                        showSearch
                        allowClear
                        placeholder="选择或输入职位关键词"
                        getPopupContainer={triggerNode => triggerNode.parentElement}
                    >
                        {keywords?.map(item => (
                            <Option
                                value={item.skill}
                                key={item.skill}
                                disabled={
                                    form.getFieldValue('skillList')?.length >= 8 &&
                                    !form.getFieldValue('skillList')?.includes(item.skill)
                                }
                            >
                                {item.skill}
                            </Option>
                        ))}
                    </Select>
                )}
            </Spin>
        </Form.Item>
    );
    const renderWarnIcon = style => <Icon style={style || {}} type="warning" theme="twoTone" twoToneColor="#faad14" />;
    const renderWarnLabel = text => (
        <div style={{ position: 'relative', display: 'inline-block', overflowX: 'visible' }}>
            {renderWarnIcon({
                position: 'absolute',
                top: 14,
                left: -30,
                fontSize: '12px'
            })}

            {text}
        </div>
    );
    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={loading || dictLoading}
            extra={data?.channelLogoUrl && <img height="44" src={data?.channelLogoUrl || ''} alt="BOSS直聘" />}
        >
            <BottomAction>
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <Alert
                style={{ marginBottom: 24 }}
                message={
                    <div>
                        注：加&nbsp;
                        {renderWarnIcon()}
                        &nbsp;内容在确认发布后，将无法修改
                    </div>
                }
                type="warning"
            />
            <Form {...formItemLayout} className="ant-advanced-search-form">
                <Form.Item label={renderWarnLabel('职位类型')}>
                    {getFieldDecorator('jobType', { rules: [{ required: true, message: '请选择职位类型' }] })(
                        <Select disabled={data?.hasRelease} placeholder="选择职位类型">
                            {renderJobTypeOptions()}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label={renderWarnLabel('职位名称')}>
                    {getFieldDecorator('positionName', {
                        rules: [{ required: true, message: '请输入职位名称' }]
                    })(<Input disabled={data?.hasRelease} placeholder="请输入职位名称" />)}
                </Form.Item>

                {/* <Form.Item label="工作地址">
                    {getFieldDecorator('Geocoder', { rules: [{ required: true, message: '请输入工作地址' }] })(
                        <Select placeholder="请输入工作地址">{renderWorkPlaceOptions()}</Select>
                    )}
                </Form.Item> */}
                <Form.Item label="经验和学历">
                    <Row>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 0 }}>
                                {getFieldDecorator('experience', {
                                    rules: [{ required: true, message: '请选择经验' }]
                                })(<Select placeholder="选择经验">{renderOptions(workExperience)}</Select>)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 0, marginLeft: 20 }}>
                                {getFieldDecorator('degree', {
                                    rules: [{ required: true, message: '请选择学历' }]
                                })(<Select placeholder="选择学历">{renderOptions(educationDegree)}</Select>)}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item label="工作地址">{getFieldDecorator('channelWorkCityName')(<Input disabled />)}</Form.Item>
                <Form.Item label="薪资范围">{renderSalaryForm()}</Form.Item>
                <Form.Item label={renderWarnLabel('职位类别')}>
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('position', {
                            rules: [{ required: true, message: '请选择职位类别' }]
                        })(
                            <DropDownCascader
                                disabled={data?.hasRelease}
                                options={categoryTree || []}
                                placeholder="选择职位类别"
                                maxCount={1}
                                changeOnLastLevel
                                onChange={handlePositionChange}
                            />
                        )}
                    </Spin>
                </Form.Item>
                {renderSKillForm()}
                <Form.Item label="职位描述">
                    {getFieldDecorator('description', { rules: [{ required: true, message: '请输入职位描述' }] })(
                        <Input.TextArea rows={24} maxLength={5000} placeholder="请输入职位描述" />
                    )}
                </Form.Item>
            </Form>
        </Card>
    );
}

export default Form.create({})(BossForm);
